App({
  globalData: {
    baseUrl: 'http://localhost:8080',
    baseURL: 'http://localhost:8080',
    hasLogin: true,
    userInfo: {userId: 'debug', username: '调试用户'},
    isCheckingToken: false,
  },
  
  onLaunch() {

    
    // 原有登录逻辑保持不变...
    const token = wx.getStorageSync('token');
    if (!token) {
      this.globalData.hasLogin = false;
      this.globalData.isCheckingToken = false;
      this.redirectToLoginIfNeeded();
      return;
    }
    const timeout = 10000;
    const requestTask = wx.request({
      url: this.globalData.baseUrl + '/user/checkToken',
      method: 'GET',
      header: { token },
      timeout: timeout,
      success: (res) => {
        if (
            res.data &&
            typeof res.data === 'object' &&
            res.data.code === 200
        ) {
          this.globalData.hasLogin = true;
          this.globalData.userInfo = res.data.data || {};
          console.log('token有效，已登录');
        } else {
          console.warn('token无效/业务失败，跳转登录', 'res.data:', res.data);
          wx.removeStorageSync('token');
          this.globalData.hasLogin = false;
        }
      },
      fail: (err) => {
        console.error('checkToken请求失败（超时/网络错误）：', err);
        wx.removeStorageSync('token');
        this.globalData.hasLogin = false;
      },
      complete: () => {
        this.globalData.isCheckingToken = false;
        this.redirectToLoginIfNeeded();
      }
    });

    setTimeout(() => {
      if (requestTask && this.globalData.isCheckingToken) {
        requestTask.abort();
        console.error('checkToken请求超时');
        wx.removeStorageSync('token');
        this.globalData.hasLogin = false;
        this.globalData.isCheckingToken = false;
        this.redirectToLoginIfNeeded();
      }
    }, timeout);
  },
  
  // 获取真实用户信息
  getRealUserInfo() {
    const token = wx.getStorageSync('token');
    if (!token) {
      console.log('没有token，等待接口返回用户信息');
      // 不设置默认值，等待后续接口返回
      return;
    }
    
    // 调用大项目的用户信息接口
    wx.request({
      url: this.globalData.baseUrl + '/user/info',
      method: 'GET',
      header: { token },
      success: (res) => {
        if (res.data && res.data.code === 200) {
          // 使用接口返回的真实用户数据
          this.globalData.userInfo = res.data.data;
          this.globalData.userId = res.data.data.userId;
          console.log('获取到真实用户信息:', this.globalData.userInfo);
        } else {
          console.warn('获取用户信息失败，等待其他接口设置');
        }
      },
      fail: (err) => {
        console.error('请求用户信息失败:', err);
      }
    });
  },
  
  redirectToLoginIfNeeded() {
    if (this.globalData.isCheckingToken) return;
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const isLoginPage = currentPage?.route === 'pages/login/login';

    if (!this.globalData.hasLogin && !isLoginPage) {
      wx.reLaunch({
        url: '/pages/login/login',
        fail: (err) => {
          console.error('跳转登录页失败：', err);
        }
      });
    }
  }
});